<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id="page-title">Socket-Chat - WebSocket聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        #messages {
            height: 300px;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            overflow-y: scroll;
            background-color: #f9f9f9;
        }
        #message-input {
            width: 70%;
            padding: 8px;
        }
        .input-group {
            margin-bottom: 10px;
        }
        label {
            display: inline-block;
            width: 100px;
            font-weight: bold;
        }
        input[type="text"], input[type="password"] {
            padding: 6px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .status {
            color: #666;
            font-style: italic;
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <h1 id="app-title">Socket-Chat 聊天室</h1>
    <div id="name-prompt">
        <div class="input-group">
            <label for="name-input">用户名:</label>
            <input type="text" id="name-input" placeholder="请输入用户名">
        </div>
        <div class="input-group">
            <label for="room-input">房间名:</label>
            <input type="text" id="room-input" placeholder="请输入聊天室名称">
        </div>
        <div class="input-group">
            <label for="password-input">密码:</label>
            <input type="password" id="password-input" placeholder="请输入房间密码（可选）">
        </div>
        <button onclick="connect()">加入聊天室</button>
        <p class="status" id="connection-status"></p>
    </div>
    <div id="chat-container" style="display: none;">
        <div id="messages"></div>
        <div>
            <input type="text" id="message-input" placeholder="在此输入消息...">
            <button onclick="sendMessage()">发送</button>
        </div>
        <div>
            <input type="file" id="file-input">
            <button onclick="uploadFile()">上传文件</button>
        </div>
        <p class="status" id="send-status"></p>
    </div>

    <script>
        let socket;
        
        /**
         * Connect to the chat server with user credentials
         */
        function connect() {
            const name = document.getElementById('name-input').value.trim();
            const room = document.getElementById('room-input').value.trim();
            const password = document.getElementById('password-input').value.trim();
            
            if (!name || !room) {
                alert('请输入用户名和房间名');
                return;
            }
            
            console.log('开始连接WebSocket服务器');
            // Update connection status
            document.getElementById('connection-status').textContent = '连接中...';
            
            // Use relative path for WebSocket connection
            const projectName = window.location.pathname.split('/')[1];
            socket = new WebSocket(`ws://${window.location.host}/${projectName}/ws`);
            
            socket.onopen = () => {
                console.log('WebSocket连接已建立');
                document.getElementById('connection-status').textContent = '认证中...';
                // 发送认证信息（用户名、房间名、密码），用换行符分隔
                const authInfo = name + '\n' + room + '\n' + password;
                console.log('发送认证信息:', authInfo);
                socket.send(authInfo);
            };
            
            socket.onmessage = (event) => {
                const data = event.data;
                console.log('收到服务器消息:', data);
                
                // 处理认证失败
                if (data === '密码错误，连接已关闭') {
                    console.log('认证失败：密码错误');
                    document.getElementById('connection-status').textContent = '认证失败：密码错误';
                    alert('认证失败：密码错误');
                    socket.close();
                    return;
                }
                
                // 处理其他认证错误
                if (data === '认证格式无效，请刷新后重试') {
                    console.log('认证错误：格式无效');
                    document.getElementById('connection-status').textContent = '认证错误：格式无效';
                    alert('认证错误：格式无效');
                    socket.close();
                    return;
                }
                
                // 处理连接成功的消息
                if (data === '连接成功，已加入聊天室') {
                    console.log('连接成功，已加入聊天室');
                    // Clear connection status on successful authentication
                    document.getElementById('connection-status').textContent = '';
                    
                    // Switch to chat view on successful connection
                    document.getElementById('name-prompt').style.display = 'none';
                    document.getElementById('chat-container').style.display = 'block';
                    return;
                }
                
                // Display message in chat
                const messagesDiv = document.getElementById('messages');
                const messageElement = document.createElement('p');
                messageElement.textContent = data;
                messagesDiv.appendChild(messageElement);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
                console.log('显示消息:', data);
            };
            
            socket.onclose = () => {
                console.log('WebSocket连接已关闭');
                document.getElementById('connection-status').textContent = '与服务器断开连接';
                alert('与服务器断开连接');
            };
            
            socket.onerror = (error) => {
                console.log('WebSocket发生错误:', error);
                document.getElementById('connection-status').textContent = '连接发生错误';
                console.error('WebSocket错误:', error);
            };
        }
        
        /**
         * Send a message to the chat server
         */
        function sendMessage() {
            const input = document.getElementById('message-input');
            const message = input.value.trim();
            
            if (!message) {
                document.getElementById('send-status').textContent = '不能发送空消息';
                setTimeout(() => {
                    document.getElementById('send-status').textContent = '';
                }, 2000);
                return;
            }
            
            if (socket && socket.readyState === WebSocket.OPEN) {
                console.log('发送消息:', message);
                socket.send(message);
                input.value = '';
                document.getElementById('send-status').textContent = '消息已发送';
                setTimeout(() => {
                    document.getElementById('send-status').textContent = '';
                }, 2000);
            } else {
                console.log('无法发送消息：未连接到服务器');
                document.getElementById('send-status').textContent = '未连接到服务器';
                setTimeout(() => {
                    document.getElementById('send-status').textContent = '';
                }, 2000);
            }
        }
        
        // Send message on Enter key press
        document.getElementById('message-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        /**
         * Upload a file to the server
         */
        function uploadFile() {
            const fileInput = document.getElementById('file-input');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请选择一个文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            // Use relative path for upload
            const projectName = window.location.pathname.split('/')[1];
            fetch(`/${projectName}/upload`, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('上传失败');
                }
            })
            .then(data => {
                console.log('文件上传成功:', data);
                alert('文件上传成功');
                // Clear file input
                fileInput.value = '';
                
                // Display file link in chat
                const messagesDiv = document.getElementById('messages');
                const messageElement = document.createElement('p');
                messageElement.innerHTML = `文件已上传: <a href="/${projectName}/download/${file.name}" target="_blank">${file.name}</a>`;
                messagesDiv.appendChild(messageElement);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
                
                // Send message to chat room
                if (socket && socket.readyState === WebSocket.OPEN) {
                    const name = document.getElementById('name-input').value.trim();
                    socket.send(`${name} 上传了文件: ${file.name}，下载地址：${window.location.origin}/${projectName}/download/${file.name}`);
                }
            })
            .catch(error => {
                console.error('文件上传失败:', error);
                alert('文件上传失败: ' + error.message);
            });
        }
    </script>
</body>
</html>